export const baseURL = "https://wx.ledusports.com"; //prod-api
// export const baseURL = 'https://ledu.hytytj.com'
const request = ({ url, data, method, loading }) => {
  let header = { "Content-Type": "application/json" };
  // header["Authorization"] = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJvcGVuSWQiOiJvejNEVTFIME5CODJXS3pKUm1GUF9sdWVkN1p3IiwiaWF0IjoxNzQ2NjE3MzI3LCJ1c2VySWQiOjg0MDV9.WngSE7sU5nELxZVoyf7XK4NjIFheIvkwiKJM15Iszzk"
  if (uni.getStorageSync("token")) {
    header["Authorization"] = uni.getStorageSync("token") || ""; // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  return new Promise((resolve, reject) => {
    !loading && uni.showLoading({title: '加载中...', mask: true});
    uni.request({
      url: baseURL + url,
      method: method || "POST",
      data,
      header,
      timeout: 10000,
      success: (res) => {
        const code = res.data.code;
        if(code==200) {
          resolve(res.data);
        } else if (code == 401) {
          //退出登录
          console.log('登录失效');
          uni.showToast({
            title: "请先登录",
            icon: "none",
            duration: 2000,
          });
          uni.reLaunch({
            url: "/pages/login",
          });
          reject("error");
        } else {
          reject("error");
        }
      },
      fail: (err) => {
        reject(err);
      },
      complete: (err)=>{
        !loading && uni.hideLoading();
        if(err.data && err.data.code!==200) {
          uni.showToast({
            title: err.data.error || err.data.msg || '请求失败',
            icon: "none",
            duration: 2000,
          });
        }
        if(err.errMsg=='request:fail timeout') {
          uni.showToast({
            title: '请求超时',
            icon: "none",
            duration: 2000,
          });
        }
      }
    });
  });
};

export default request;
